package org.example.laboratorymanagement.controller;

import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import lombok.extern.slf4j.Slf4j;
import org.example.laboratorymanagement.pojo.Homework;
import org.example.laboratorymanagement.pojo.PageBean;
import org.example.laboratorymanagement.pojo.Result;
import org.example.laboratorymanagement.service.HomeworkService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.List;

@CrossOrigin
@Slf4j
@RestController
@RequestMapping("/homeworks")
public class HomeworkController {

    @Autowired
    private HomeworkService homeworkService;

    @PostMapping
    public Result insert(@RequestBody Homework homework){
        log.info("添加实验报告：{}",homework);
        homeworkService.insert(homework);
        return Result.success();
    }

    @PostMapping("/insertBatch")
    public Result insertBatch(MultipartFile file) throws IOException {
        ExcelReader reader = ExcelUtil.getReader(file.getInputStream());
        List<Homework> homeworks = reader.readAll(Homework.class);
        log.info("批量添加学生实验报告：{}",homeworks);
        try {
            homeworkService.insertBatch(homeworks);
        } catch (Exception e) {
            return Result.error("数据库批量导入出错！");
        }

        return Result.success();

    }

    @PutMapping
    public Result update(@RequestBody Homework homework){
        log.info("修改实验报告：{}",homework);
        homeworkService.update(homework);
        return Result.success();
    }

    @DeleteMapping("/{ids}")
    public Result delete(@PathVariable List<Integer> ids){
        log.info("删除实验报告：{}",ids);
        homeworkService.delete(ids);
        return Result.success();
    }

    @GetMapping
    public Result pageHomeworks(@RequestParam(defaultValue = "1") Integer page,
                               @RequestParam(defaultValue = "10") Integer pageSize,
                               String username, String lesson, String susername, String experiment,
                               String local, @DateTimeFormat(pattern = "yyyy-MM-dd") String date,
                               String time){
        log.info("分页查询学生，参数：{},{},{},{},{},{},{},{},{}",page,pageSize,username,lesson,
                susername,experiment,local,date,time);
        PageBean pageBean = homeworkService.pageHomeworks(page, pageSize, username, lesson, susername, experiment,
                local, date, time);
        return Result.success(pageBean);
    }


}
